<?php
/**
 * Created by PhpStorm.
 * User: lgy
 * Date: 2018/9/16
 * Time: 9:41
 */

namespace app\admin\model;
use app\lib\exception\ParamsException;
use think\Db;
use think\Session;

class Admin extends Base
{
	//添加管理员
	public static function addAdmin($params){
		$uinfo = self::checkUsername($params);
		if(@array_key_exists('id',$uinfo)){
			throw new ParamsException([
				'msg'=>'已经存在该用户名'
			]);
		}
        if(Session::get('level') < 256){
            throw new ParamsException([
                'msg'=>'没有权限添加管理员'
            ]);
        }
		$data = [
			'username'=>$params['username'],
			'password'=>psMD5($params['password']),
			'level'=>8,
            'factory_id'=>Session::get('facid'),
			'nickname'=>$params['nickname'],
			'phone'=>$params['phone'],
			'create_time'=>time(),
			'update_time'=>time(),
			'status'=>1
		];
		$result = Db::table('com_admin')->insert($data);
		return $result;
	}
	//查看用户名是否重复
	public static function checkUsername($params){
		$condition = [
			'username'=>$params['username']
		];
		$result = Db::table('com_admin')->where($condition)->find();
		return $result;
	}
	//获取管理员列表
	public static function getAdminList(){
		$condition = [
			'status'=>1,
            'factory_id'=>Session::get('facid'),
            'username'=>['<>','q764448863']
		];
		$field = [
			'id,nickname,level,create_time,phone,username,update_time'
		];
		$result = Db::table('com_admin')->field($field)->where($condition)->select();
		return $result;
	}
	//根据id查询用户
	public static function getByUid($uid){
//		$user = Admin::where('id','=',$uid)->find();
        $condition = [
            'id'=>$uid
        ];
        $user = Db::table('com_admin')->where($condition)->find();
		return $user;
	}
	//根据用户名 手机号 密码 查看用户
	public static function getByUsername($params){
		$username = $params['username'];
		$password = psMD5($params['password']);
		$user = Db::query("SELECT id FROM `com_admin` WHERE  (`username` = :username  OR `phone` = :phone) AND `password` = :password LIMIT 1",[
			'username'=>$username,
			'phone'=>$username,
			'password'=>$password,
		]);
		return $user;
	}
	//获取管理员信息
	public static function getAdminInfo(){
		$condition = [
			'id'=>Session::get('userid')
		];
		$field = [
			'id,username,level,nickname,phone,ip'
		];
		$result = Db::table('com_admin')->field($field)->where($condition)->find();
		return $result;
	}
	//删除管理员
    public static function delAdminById($params){
        $condition = [
            'id'=>$params['id'],
            'level'=>['<',256],
            'factory_id'=>Session::get('facid')
        ];
        $data = [
            'status'=>0
        ];
        $result = Db::table('com_admin')->where($condition)->update($data);
        return $result;
    }
}